package cli

import (
	"fmt"
	"strings"
)

func HelpCommand() Option {
	validArgsFunction := ValidArgsFunction(func(c *Command, args []string, toComplete string) ([]string, ShellCompDirective) {
		var completions []string
		cmd, _, e := c.Root().Find(args)
		if e != nil {
			return nil, ShellCompDirectiveNoFileComp
		}
		if cmd == nil {
			cmd = c.Root()
		}
		for _, subCmd := range cmd.Commands() {
			if subCmd.IsAvailableCommand() {
				if strings.HasPrefix(subCmd.Name(), toComplete) {
					completions = append(completions, fmt.Sprintf("%s\t%s", subCmd.Name(), subCmd.Short))
				}
			}
		}
		return completions, ShellCompDirectiveNoFileComp
	})

	run := Run(func(c *Command, args []string) {
		cmd, _, e := c.Root().Find(args)
		if cmd == nil || e != nil {
			c.Printf("Unknown help topic %#q\n", args)
			CheckErr(c.Root().Usage())
		} else {
			cmd.InitDefaultHelpFlag()
			CheckErr(cmd.Help())
		}
	})

	help := New(Use("help [command]"), run, validArgsFunction)

	return OptionApply(func(c *Command) { c.SetHelpCommand(&help.Command) })
}
